package org.springframework.sandbox.base;

import java.text.SimpleDateFormat;
import java.util.concurrent.Executor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;



public class LogInterceptor implements HandlerInterceptor{

	private final Logger log = LoggerFactory.getLogger(getClass().getName());
	 
	private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		long beginTime = System.currentTimeMillis(); //开始时间 
		 
	    startTimeThreadLocal.set(beginTime); //线程绑定变量（该数据只有当前请求的线程可见） 
	 
	    log.info("Start: {}", new SimpleDateFormat("hh:mm:ss.SSS").format(beginTime));
	 
	    return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView != null){
			 
		      log.info("ViewName: " + modelAndView.getViewName());
		 
		    }
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("Address：" + request.getRequestURI() + "，Method：" + request.getMethod());
		 
	    long beginTime = startTimeThreadLocal.get(); //得到线程绑定的局部变量（开始时间） 
	 
	    long endTime = System.currentTimeMillis(); //结束时间 
	 
	    log.info("End：{}", new SimpleDateFormat("hh:mm:ss.SSS").format(endTime)); 
	    log.info("CostTime：{}ms",endTime-beginTime);
	 
		
	}

	
}
